package com.frikinet.tools.gui;

import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;

import com.frikinet.tools.i18n.FI18N;
import com.frikinet.tools.i18n.Translable;

public class FButton extends JButton implements Translable
{
	private static final long serialVersionUID = 1L;

	private FI18N i18n = null;
	
	public FButton()
	{
		super();
	}
	
	public FButton(String command, ActionHandler handler)
	{
		super();
		setActionCommand(command);
		addActionListener(handler);
	}

	public FButton(Action a)
	{
		super(a);
	}

	public FButton(Icon icon)
	{
		super(icon);
	}
	
	public FButton(Icon icon, String command, ActionHandler handler)
	{
		super(icon);
		setActionCommand(command);
		addActionListener(handler);
	}

	public FButton(String text, Icon icon)
	{
		super(text, icon);
	}
	
	public FButton(String text, Icon icon, String command, ActionHandler handler)
	{
		super(text, icon);
		setActionCommand(command);
		addActionListener(handler);
	}

	public FButton(String text)
	{
		super(text);
	}
	
	public FButton(String text, String command, ActionHandler handler)
	{
		super(text);
		setActionCommand(command);
		addActionListener(handler);
	}

	public FI18N getI18n()
	{
		return i18n;
	}

	public void setI18N(FI18N i18n)
	{
		this.i18n = i18n;
	}
	
	public void translate()
	{
		setFocusPainted(false);
		String text = getText();
		String tooltip = getToolTipText();
		if(i18n != null)
		{
			super.setText(parseName(i18n.translate(text)));
			if(tooltip != null && !tooltip.equals(""))
				super.setToolTipText(i18n.translate(tooltip));
		}
		else
		{
			super.setText(parseName(text));
		}
	}
	
	private String parseName(String text)
	{
		String stripString = text.replaceAll("_", "");
		int index = text.indexOf('_');
		if(index >= 0)
			setMnemonic(text.charAt(index+1));
		return stripString;
	}
	
	public void setResourceIcon(String path)
	{
		this.setIcon(new ImageIcon(ClassLoader.getSystemResource(path)));
	}
}
